#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"

#define Fan_GPIO_IDX 2
#define Fan_PWM_PORT 2
int isOpenPwmfan = 1;

void init_fan()
{
    int ret = IoTGpioInit(Fan_GPIO_IDX);
    printf("fan gpio init ret = %d\n",ret);
    ret = IoTGpioSetFunc(Fan_GPIO_IDX, IOT_GPIO_FUNC_GPIO_2_PWM2_OUT);
    printf("IoTGpioSetFunc ret = %d\n",ret);
    ret = IoTPwmInit(Fan_PWM_PORT);
    printf("IoTPwmInit ret = %d\n",ret);

}


int fan_speed(int speed){
    if( speed <= 0){
        int ret = IoTPwmStop(Fan_PWM_PORT);
        return ret;
    }   

    if( speed >= 5 ){
        speed = 5;
    }

    int ret = IoTPwmStart(Fan_PWM_PORT, speed,4000);
    printf("IoTPwmStart ret = %d\n",ret);
    return ret;
}

int fan_task()
{
    init_fan();
     
    for( int i = 5; i >= 0; i-- ){
        printf("==> set fan speed %d\n",i);
    
        fan_speed(i);
        sleep(2);
    }
}

static void fan_demo(void)
{
    osThreadAttr_t attr;    
    attr.name = "fan_task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = 20; 
    if (osThreadNew(fan_task, NULL, &attr) == NULL) {
        printf("[hello_task] Failed to create task2!\n");
    }

}
SYS_RUN(fan_demo);